﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace DotNet.Utilities
{
    /// <summary>
    /// 字符串处理帮助类
    /// </summary>
    public class StringUtil
    {
        #region 字符串处理

        public static string HtmlDecode(string raw)
        {
            return HttpUtility.HtmlDecode(raw);
        }

        public static string HtmlEncode(string raw)
        {
            return HttpUtility.HtmlEncode(raw);
        }

        public static string UrlDecode(string raw)
        {
            return HttpUtility.UrlDecode(raw);
        }
        public static string UrlDecode(string raw, Encoding encode)
        {
            return HttpUtility.UrlDecode(raw, encode);
        }

        public static string UrlEncode(string raw)
        {
            return HttpUtility.UrlEncode(raw);
        }
        public static string UrlEncode(string raw, Encoding encode)
        {
            return HttpUtility.UrlEncode(raw, encode);
        }
        /// <summary>
        /// 替换字符串/正则
        /// </summary>
        /// <param name="raw">源字符串</param>
        /// <param name="oldStr">要替换的字符串/正则</param>
        /// <param name="newStr">新字符串</param>
        /// <returns></returns>
        public static string Replace(string raw, string oldStr, string newStr)
        {
            return Regex.Replace(raw, oldStr, newStr);
        }
        /// <summary>
        /// 替换指定索引的字符串/正则
        /// </summary>
        /// <param name="raw">源字符串</param>
        /// <param name="oldStr">要替换的字符串/正则</param>
        /// <param name="newStr">新字符串</param>
        /// <param name="index">要替换第几个</param>
        /// <returns></returns>
        public static string Replace(string raw, string oldStr, string newStr, int index)
        {
            int i = 0;
            string str = Regex.Replace(raw, oldStr, new MatchEvaluator(delegate(Match m) { return (i++ == index) ? newStr : m.Value; }));
            return str;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <param name="matches"></param>
        public static void WriteMatches(string text, MatchCollection matches)
        {
            Console.WriteLine("Original text was: \n\n" + text + "\n");
            Console.WriteLine("No. of matches: " + matches.Count);
            foreach (Match nextMatch in matches)
            {
                int index = nextMatch.Index;
                string result = nextMatch.ToString();
                int charsBefore = (index < 5) ? index : 5;
                int fromEnd = text.Length - index - result.Length;
                int charsAfter = (fromEnd < 5) ? fromEnd : 5;
                int charsToDisplay = charsBefore + charsAfter + result.Length;

                Console.WriteLine("Index: {0}, \tString: {1}, \t{2}",
                   index, result,
                   text.Substring(index - charsBefore, charsToDisplay));

            }
        }
        public static string RemoveScriptIframe(string raw)
        {
            return Regex.Replace(raw, @"<(/?)(script|iframe)([^>]*)>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }

        public static string RemoveHtml(string raw)
        {
            return Regex.Replace(raw, @"<.+?>", "");
        }

        public static string Left(string str, int length)
        {
            return str.Length > length ? str.Substring(0, length) : str;
        }

        public static string Right(string str, int length)
        {
            return str.Length > length ? str.Substring(str.Length - length) : str;
        }

        #endregion

        #region 类型转换
        public static int ToInt(string str)
        {
            int i = 0;
            int.TryParse(str, out i);
            return i;
        }

        public static double ToDouble(string str)
        {
            double d = 0d;
            double.TryParse(str, out d);
            return d;
        }

        public static DateTime ToDateTime(string str)
        {
            DateTime dt = DateTime.Now;
            int len = str.Length;
            if (len < 8) return dt;
            
            if (len == 8)
            {
                string y = str.Substring(0, 4);
                string m = Regex.Replace(str.Substring(4, 2), @"\D*", "");
                string d = Regex.Replace(str.Substring(6, 2), @"\D*", "");

                str = y + "-" + m + "-" + d;
            }
            if (DateTime.TryParse(str, out dt)) return dt;
            else return DateTime.Now;
        }
		public static string ToUnicode(string str)
        {
            byte[] data = Encoding.BigEndianUnicode.GetBytes(str);
            int i = 0;
            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
            {
                if (i++ % 2 == 0) sb.Append("\\u");
                sb.AppendFormat("{0:X2}", b);
            }
            return sb.ToString();
        }
        #endregion

        /// <summary>
        /// 随机一个字符串[1-9A-Z]
        /// </summary>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static string RandomCode(int length)
        {
            string s = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
            Random r = new Random();
            string code = "";
            while (code.Length < length)
            {
                code += s[r.Next(0, 33)];
            }
            return code;
        }

        /// <summary>
        /// 是否为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int IsNumeric(string str)
        {
            int i;
            if (str != null && System.Text.RegularExpressions.Regex.IsMatch(str, @"^-?\d+$"))
                i = int.Parse(str);
            else
                i = -1;
            return i;
        }

        public static bool IsNumeric2(string number)
        {
            try
            {

                for (int i = 0; i < number.Length; i++)
                {
                    if (!char.IsNumber(number, i))
                    {
                        return false;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// 判断是否是数字
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public bool IsNumeric3(string number)
        {
            try
            {
                int.Parse(number);
                return true;
            }
            catch
            {
                return false;
            }
        } 

    }
}
